package com.rv.nats.autoconfigure;

import com.rv.nats.annotation.EnableNatsDiscovery;
import com.rv.nats.configuration.NatsConfiguration;
import com.rv.nats.configuration.NatsConnectionFactory;
import com.rv.nats.core.*;
import com.rv.nats.listener.NatsConnectionListener;
import com.rv.nats.listener.NatsErrorListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
 * @author .sun
 * @date 2022/1/14
 **/
@Slf4j
@Configuration
@EnableNatsDiscovery(basePackages = {"com.rv.**.nats"})
@EnableConfigurationProperties(NatsProperties.class)
public class NatsAutoConfiguration {

    private final NatsProperties properties;


    public NatsAutoConfiguration(NatsProperties properties) {
        this.properties = properties;
    }


    @ConditionalOnMissingBean
    @Bean
    public NatsConfiguration natsConfiguration() {
        NatsConnectionFactory factory = new NatsConnectionFactory();
        factory.setConfigurationProperties(properties);
        factory.setConnectionListener(new NatsConnectionListener());
        factory.setErrorListener(new NatsErrorListener());
        return factory.getObject();
    }


    @Bean
    @ConditionalOnProperty(value = "spring.nats.enable", havingValue = "true")
    public ApplicationNatsHandler applicationNatsHandler(NatsConfiguration configuration) {
        ApplicationNatsHandler natsHandler = new ApplicationNatsHandler();
        try {
            natsHandler.init(configuration.builder(), true);
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }
        return natsHandler;
    }


}
